package com.bkhc.partner.repository;

import com.bkhc.partner.entity.Employee;
import com.bkhc.partner.entity.PartnerBrand;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.stereotype.Repository;
import org.springframework.util.StringUtils;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.ArrayList;
import java.util.List;

@Repository
public interface PartnerBrandRepository extends JpaRepository<PartnerBrand,String>, JpaSpecificationExecutor<PartnerBrand> {
    default Page<PartnerBrand> findAll(PartnerBrand partnerBrand, Pageable pageable){
        return findAll(new Specification<PartnerBrand>() {
            @Override
            public Predicate toPredicate(Root<PartnerBrand> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
                List<Predicate> predicate = new ArrayList<>();
                if(!StringUtils.isEmpty(partnerBrand.getBrandCode())){
                    predicate.add(criteriaBuilder.equal(root.get("brandCode").as(String.class), partnerBrand.getBrandCode()));
                }
                if(!StringUtils.isEmpty(partnerBrand.getBrandName())){
                    predicate.add(criteriaBuilder.like(root.get("brandName").as(String.class),"%"+ partnerBrand.getBrandName()+"%"));
                }
                if(!StringUtils.isEmpty(partnerBrand.getPartnerCode())){
                    predicate.add(criteriaBuilder.equal(root.get("partnerCode").as(String.class), partnerBrand.getPartnerCode()));
                }
                Predicate[] pre = new Predicate[predicate.size()];

                return criteriaQuery.where(predicate.toArray(pre)).getRestriction();
            }
        },pageable);


    }
    void deleteAllByPartnerCode(String partnerCode);

    List<PartnerBrand> findByPartnerCode(String partnerCode);
}
